package com.yutel.amote;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.yutel.amote.packet.AbstractPacket;
import com.yutel.amote.packet.ClientHelper;
import com.yutel.amote.packet.Protocol;
import com.yutel.amote.service.AmoteConstant;

public class TouchActivity extends Activity implements OnTouchListener,
		OnGestureListener {
	final String TAG = "Touch";
	GestureDetector mGesture = null;
	ClientHelper ch = null;
	ImageView iv = null;
	int FLING_MIN_VELOCITY = 10;
	int FLING_MIN_DISTANCE = 10;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.touchpad);
		mGesture = new GestureDetector(this);
		AmoteConstant con = AmoteConstant.getInstance(this);
		ch = new ClientHelper(con.getKey("serverIP"), con.getKey("serverPort"));
		iv = (ImageView) findViewById(R.id.touch);
		iv.setOnTouchListener(this);
		iv.setLongClickable(true);
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "TouchActivity->onPause");
		ch.finalize();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "TouchActivity->onResume");
	}

	@Override
	public boolean onTouch(View v, MotionEvent me) {
		return mGesture.onTouchEvent(me);
	}

	// 用户轻触触摸屏，由1个MotionEvent ACTION_DOWN触发
	@Override
	public boolean onDown(MotionEvent arg0) {
		Log.d(TAG, "down");
		return false;
	}

	// 用户按下触摸屏、快速移动后松开，由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE, 1个ACTION_UP触发
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// 参数解释：
		// e1：第1个ACTION_DOWN MotionEvent
		// e2：最后一个ACTION_MOVE MotionEvent
		// velocityX：X轴上的移动速度，像素/秒
		// velocityY：Y轴上的移动速度，像素/秒
		// 触发条件 ：
		// X轴的坐标位移大于FLING_MIN_DISTANCE，且移动速度大于FLING_MIN_VELOCITY个像素/秒

		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling left
			Log.d(TAG, "Fling Left");
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling right
			Log.d(TAG, "Fling Right");
		}
		if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE
				&& Math.abs(velocityY) > FLING_MIN_VELOCITY) {
			// Fling left
			Log.d(TAG, "Fling Down");
		} else if (e2.getY() - e1.getY() > FLING_MIN_DISTANCE
				&& Math.abs(velocityY) > FLING_MIN_VELOCITY) {
			// Fling right
			Log.d(TAG, "Fling Up");
		}
		return false;
	}

	// 用户长按触摸屏，由多个MotionEvent ACTION_DOWN触发
	@Override
	public void onLongPress(MotionEvent arg0) {
		Log.d(TAG, "Long Press");
	}

	// 用户按下触摸屏，并拖动，由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE触发
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling left
			Log.d(TAG, "Scroll Left");
			AbstractPacket ap = new AbstractPacket(Protocol.Command.move);
			ap.setValue(e1.getX() + "," + e1.getY() + ";" + e2.getX() + ","
					+ e2.getY());
			sendMsg(ap);
		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling right
			Log.d(TAG, "Scroll Right");
			AbstractPacket ap = new AbstractPacket(Protocol.Command.move);
			ap.setValue(e1.getX() + "," + e1.getY() + ";" + e2.getX() + ","
					+ e2.getY());
			sendMsg(ap);
		}
		if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE
				&& Math.abs(velocityY) > FLING_MIN_VELOCITY) {
			// Fling left
			Log.d(TAG, "Scroll Down");
			AbstractPacket ap = new AbstractPacket(Protocol.Command.move);
			ap.setValue(e1.getX() + "," + e1.getY() + ";" + e2.getX() + ","
					+ e2.getY());
			sendMsg(ap);
		} else if (e2.getY() - e1.getY() > FLING_MIN_DISTANCE
				&& Math.abs(velocityY) > FLING_MIN_VELOCITY) {
			// Fling right
			Log.d(TAG, "Scroll Up");
			AbstractPacket ap = new AbstractPacket(Protocol.Command.move);
			ap.setValue(e1.getX() + "," + e1.getY() + ";" + e2.getX() + ","
					+ e2.getY());
			sendMsg(ap);
		}
		return false;
	}

	public void sendMsg(AbstractPacket ap) {
		if (!ch.send(ap)) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					TouchActivity.this);
			builder.setTitle("警告")
					.setMessage("服务端无法连接,请重新设置或检查服务端!")
					.setCancelable(false)
					.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent control = new Intent(
											TouchActivity.this,
											ClientCfgActivity.class);
									startActivity(control);
								}
							});
			builder.show();
		}
	}

	// 用户轻触触摸屏，尚未松开或拖动，由一个1个MotionEvent ACTION_DOWN触发
	// 注意和onDown()的区别，强调的是没有松开或者拖动的状态
	@Override
	public void onShowPress(MotionEvent arg0) {
		Log.d(TAG, "Show Press");
	}

	// 用户（轻触触摸屏后）松开，由一个1个MotionEvent ACTION_UP触发
	@Override
	public boolean onSingleTapUp(MotionEvent arg0) {
		Log.d(TAG, "Single Tap Up");
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.control, menu);
		menu.removeItem(R.id.menui_server_control);
		menu.removeItem(R.id.menui_client_touch);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menui_appType:
			Intent intent = new Intent(TouchActivity.this,
					ApptypeActivity.class);
			startActivity(intent);
			break;
		case R.id.menui_server_control:
			Log.d(TAG, "menui_server_control");
			break;
		case R.id.menui_client_touch:
			Log.d(TAG, "menui_server_control");
			break;
		case R.id.menui_touch_config:
			Intent control = new Intent(TouchActivity.this,
					ClientCfgActivity.class);
			startActivity(control);
			break;
		case R.id.menui_client_sensor:
			Intent sensor = new Intent(TouchActivity.this, SensorActivity.class);
			startActivity(sensor);
			break;
		case R.id.menui_client_borad:
			Intent borad = new Intent(TouchActivity.this, BoardActivity.class);
			startActivity(borad);
			break;
		default:
			Log.e(TAG, "default=" + item.getItemId());
		}
		return true;
	}

	public void showMsg(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
}